﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web.UI;
using EasyWeixin.CommonAPIs;
using EasyWeixin.Entities.JsonResult;
using Newtonsoft.Json;
using RaceList.activity.help;
using RaceList.activity.util;

namespace RaceList.activity.mhalloween
{
    /// <summary>
    ///     ?relay=first&cycle=123
    ///     ?relay=123
    /// </summary>
    public partial class Relaygame : Page, IAuthWeixin
    {
        protected Activity_Relay HelperRelay { get; set; }

        protected WxConfigResult WxConfig { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            string cycleId = Request.QueryString[Parameters.cycle];
            string relayId = Request.QueryString[Parameters.relay];

            if (relayId == Parameters.first) //每个人第一次玩
            {
                #region

                if (string.IsNullOrEmpty(cycleId))
                {
                    Response.Redirect404(Request.Url.ToString());
                }
                else
                {
                    int id = Convert.ToInt32(cycleId);
                    Activity_Cycle cycle = RelayQuery.GetCycle(id);
                    if (cycle != null)
                    {
                        SessionHelp.CycleId = id;
                        //这里先添加一条空记录，然后最后提交成绩的时候变成修改记录得了
                        var relay = AddRelay();

                        var userChengji = SessionHelp.UserChengji;
                        userChengji.FirstAddRelayId = relay.Id;
                        SessionHelp.UserChengji = userChengji;

                        GetAward(relay); //中奖
                    }
                    else
                    {
                        Response.Redirect404(Request.Url.ToString());
                    }
                }
                #endregion
            }
            else //接着别人跑
            {
                #region
                if (string.IsNullOrEmpty(relayId))
                {
                    Response.Redirect404(Request.Url.ToString());
                }
                else
                {
                    Activity_Relay relay = RelayQuery.GetRelay(Convert.ToInt32(relayId));
                    if (relay != null)
                    {
                        SessionHelp.CycleId = relay.CycleId;
                        HelperRelay = relay;
                        if (CheckCanHelp())
                        {
                            AddHelpSession(relay);
                        }
                        else
                        {
                            string resultUrl = "Relayresult.aspx?" + Parameters.relay + "=" + HelperRelay.Id;
                            Response.Write(
                                string.Format(
                                    "<html><head></head><script>window.location.href='{0}'</script><body></body></html>"
                                    , resultUrl));
                            Response.End();
                        }
                    }
                    else
                    {
                        Response.Redirect404(Request.Url.ToString());
                    }
                }
                #endregion
            }

            InitWxConfig();
            GetScore();
        }


        private Activity_Relay AddRelay()
        {
            //如果是第一次玩，进入游戏界面后就默认添加一条空记录，然后在最后提交的时候就变成了修改该记录了
            return RelayQuery.AddRelay(new Activity_Relay()
            {
                AddTime = DateTime.Now,
                ClickNum = 0,
                Score = 0,
                SumScore = 0,
                WeixinUserId = SessionHelp.UserData.WeixinUserId,
                CycleId = SessionHelp.CycleId,
                EditTime = DateTime.Now
            });
        }

        public string Scores { get; set; }
        public void GetScore()
        {
            var score = new Score();
            for (int i = 0; i < 30; i++)
            {
                Thread.Sleep(50);
                long tick = DateTime.Now.Ticks;
                int seed = int.Parse(tick.ToString().Substring(9));
                Random ran = new Random(seed);
                var num = ran.Next(1, 10) + 10;
                score.ScoreList.Add(num);
            }
            Scores = score.ConvertToJson();
            //把这个分数加到UserChengji中
            var userChengji = SessionHelp.UserChengji;
            userChengji.Scores = score.ScoreList;
            SessionHelp.UserChengji = userChengji;
        }
        public bool IsAward { get; set; }

        /// <summary>
        /// 直接在这一步产生出一个中奖纪录
        /// </summary>
        public void GetAward(Activity_Relay relay)
        {
            //通过微信userid来判断是否存在中奖纪录
            var isExist = RelayQuery.ExistAwardUserByWeixinUserId(SessionHelp.UserData.WeixinUserId);
            if (!isExist) //不存在中奖用户的记录
            {
                if (Award())
                {
                    Activity_Awards award = RelayQuery.GetActivity_Awards();
                    if (award != null)
                    {
                        Activity_AwardUser awardUser = RelayQuery.GetActivity_AwardUser(relay.Id);
                        if (awardUser == null)
                        {
                            //这里只需要添加纪录即可，不需要wincode
                            var obj = new Activity_AwardUser
                            {
                                winCode = "",
                                isAward = false, //表示未提交用户信息
                                addTime = DateTime.Now,
                                relayId = relay.Id,
                                awardId = award.Id
                            };
                            RelayQuery.AddActivity_AwardUser(obj);

                            IsAward = true;
                        }
                    }
                }

            }
        }

        /// <summary>
        /// 是否中奖的逻辑
        /// </summary>
        /// <returns></returns>
        public bool Award()
        {
            return true;
            //如果总的奖品数量
            //int num = new Random().Next(1, 1000);
            //if (num < 10)
            //{
            //    return true;
            //}
            //return false;
        }
        public void InitWxConfig()
        {
            WxConfigResult result = CommonApi.GetWxConfigResult(ActivityConfig.MHalloweenAppId,
                ActivityConfig.MHalloweenAppSecrect, Request.Url.ToString());
            WxConfig = result;
        }

        private bool CheckCanHelp()
        {
            int loginwxid = SessionHelp.UserData.WeixinUserId;

            bool canhelp = loginwxid != HelperRelay.WeixinUserId; //如果相等的话，就是自己登录以后查看自己的也不能帮忙
            if (canhelp) //如果==true
            {
                canhelp = HelperRelay.Activity_SubRelay.Count() + 1 < ActivityConfig.MHalloweenTotalPerson;
                //参与游戏的人少于ji人为true    
                if (canhelp)
                    canhelp = RelayQuery.GetCanHelp(loginwxid, HelperRelay);
            }
            return canhelp;
        }

        private void AddHelpSession(Activity_Relay relay)
        {
            SessionHelp.UserChengji = new UserChengji
            {
                IsHelp = true,
                RelayId = relay.Id,
            };
        }

    }

    public class Score
    {
        public Score()
        {
            ScoreList = new List<double>();
        }
        public List<double> ScoreList { get; set; }

        public string ConvertToJson()
        {
            return JsonConvert.SerializeObject(this.ScoreList);
        }
    }
}